"""
下载并设置 Live2D Cubism SDK for Web
"""

import urllib.request
import zipfile
import os
import shutil
from pathlib import Path

def download_file(url, dest_path):
    """下载文件"""
    print(f"正在下载: {url}")
    print(f"目标: {dest_path}")
    
    try:
        headers = {
            'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36'
        }
        
        req = urllib.request.Request(url, headers=headers)
        
        with urllib.request.urlopen(req, timeout=60) as response:
            total_size = int(response.headers.get('Content-Length', 0))
            downloaded = 0
            chunk_size = 8192
            
            with open(dest_path, 'wb') as f:
                while True:
                    chunk = response.read(chunk_size)
                    if not chunk:
                        break
                    f.write(chunk)
                    downloaded += len(chunk)
                    
                    if total_size > 0:
                        progress = (downloaded / total_size) * 100
                        print(f"\r进度: {progress:.1f}% ({downloaded}/{total_size} bytes)", end='')
        
        print("\n✓ 下载完成")
        return True
        
    except Exception as e:
        print(f"\n✗ 下载失败: {e}")
        return False


def main():
    print("=" * 70)
    print("Live2D Cubism SDK 下载器")
    print("=" * 70)
    
    project_root = Path(__file__).parent
    sdk_dir = project_root / "cubism-sdk"
    
    print(f"\nSDK 目录: {sdk_dir}")
    
    # 由于官方SDK下载需要同意协议，我们使用 GitHub 上的开源实现
    print("\n正在下载 Live2D Web Framework...")
    print("提示: 这可能需要几分钟时间\n")
    
    # 使用 pixi-live2d-display 的完整 GitHub 仓库
    github_zip_url = "https://github.com/guansss/pixi-live2d-display/archive/refs/heads/master.zip"
    zip_path = project_root / "live2d-temp.zip"
    
    # 下载
    if not download_file(github_zip_url, zip_path):
        print("\n建议: 手动下载并解压到项目目录")
        print(f"URL: {github_zip_url}")
        return 1
    
    # 解压
    print("\n正在解压...")
    try:
        with zipfile.ZipFile(zip_path, 'r') as zip_ref:
            zip_ref.extractall(project_root / "temp_extract")
        
        # 移动到正确位置
        extract_dir = project_root / "temp_extract" / "pixi-live2d-display-master"
        if extract_dir.exists():
            if sdk_dir.exists():
                shutil.rmtree(sdk_dir)
            shutil.move(str(extract_dir), str(sdk_dir))
        
        # 清理
        shutil.rmtree(project_root / "temp_extract")
        zip_path.unlink()
        
        print("✓ 解压完成")
        
    except Exception as e:
        print(f"✗ 解压失败: {e}")
        return 1
    
    print("\n" + "=" * 70)
    print("✓ Live2D SDK 设置完成")
    print("=" * 70)
    print(f"\nSDK 位置: {sdk_dir}")
    print("\n下一步: 运行集成脚本")
    
    return 0


if __name__ == "__main__":
    import sys
    sys.exit(main())
